#include "pch.h"
#include "Image.h"
#include <memory>
#include "ErrorCodes.h"
#include "WIC.h"
#include "Texture2D.h"

using namespace Platform;
using namespace Windows::Foundation;
using namespace concurrency;
using namespace Microsoft::WRL;

using namespace DXBase;
using namespace DXBase::D2D;


Bitmap::Bitmap()
{
	watcher.Target = this;
}

void Bitmap::LoadDXData()
{
	if (!pBitmap)
	{
		if (!Context)
			throw ExHelper::CreateException(ErrorCodes::ContextNotSet);
		if (loadDX._Empty())
			throw ExHelper::CreateException(ErrorCodes::TextureEmpty);
		loadDX(this);
	}
}
void Bitmap::Create(UINT32 width, UINT32 height)
{
	ClearDXData();
	size = Windows::Foundation::Size((float)width, (float)height);
	pixelSize.width = width;
	pixelSize.height = height;
	loadDX = [width,height] (Bitmap^ me)
	{
		if (!me->Context)
			throw ExHelper::CreateException(ErrorCodes::ContextNotSet);
		D2D1_SIZE_U size = { width, height };
		D2D1_BITMAP_PROPERTIES bProps = { { DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_STRAIGHT }, 96.0f, 96.0f };
		HR2Ex(me->Context->m_d2dContext->CreateBitmap(size, bProps, me->pBitmap.GetAddressOf()));
	};
}

void Bitmap::CreateWic(String^ file)
{
	ClearDXData();
	loadDX = [file] (Bitmap^ me)
	{
		if (!me->Context)
			throw ExHelper::CreateException(ErrorCodes::ContextNotSet);

		auto src = WIC::LoadImage(file);
		HR2Ex(me->Context->m_d2dContext->CreateBitmapFromWicBitmap(src.Get(), nullptr, me->pBitmap.GetAddressOf()));

		auto s = me->pBitmap->GetSize();
		me->size = Windows::Foundation::Size(s.width, s.height);
		D2D1_SIZE_U ps = me->pBitmap->GetPixelSize();
		me->pixelSize.width = ps.width;
		me->pixelSize.height = ps.height;
	};
}

//NativeRenderTarget^ Bitmap::GetNativeTarget()
//{
//	// TODO test that
//	if (!ntarget)
//	{
//		LoadDXData();
//		ComPtr<IDXGISurface> surface;
//		HR2Ex(pBitmap.As(&surface));
//		ComPtr<ID3D11Texture2D> target;
//		HR2Ex(surface.As(&target));
//
//		ntarget = ref new NativeRenderTarget(target);
//	}
//	return ntarget;
//}
//D3D::Texture2D^ Bitmap::Snapshot()
//{
//	// TODO test that
//	LoadDXData();
//	ComPtr<IDXGISurface> surface;
//	HR2Ex(pBitmap.As(&surface));
//	ComPtr<ID3D11Texture2D> target;
//	HR2Ex(surface.As(&target));
//
//	auto result = ref new D3D::Texture2D();
//	result->InitCopy(target);
//	return result;
//}
